package org.zyj.io.idle;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.zyj.io.protocal.Message;

/**
 * 继承Netty实现的编码抽象类
 * 可以得到更加稳健的代码, 不需要管理一些复杂的细节
 * 专心处理编码问题
 */
public class MessageEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        out.writeInt(msg.getBody().length);
        out.writeInt(msg.getVersion());
        out.writeInt(msg.getOpCode());
        out.writeInt(msg.getStreamId());
        out.writeBytes(msg.getBody());
    }
}
